import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {NavController} from '@ionic/angular';
import {Utils} from '../../../providers/Utils';


@Component({
    selector: 'app-acct-balance',
    templateUrl: './acct-balance.page.html',
    styleUrls: ['./acct-balance.page.scss'],
})
export class AcctBalancePage implements OnInit {
    anyList: any;
    params: any;
    apiUrl: any;
    header: any;
    loading: any;

    // TODO: 地址配置  临时（在多个接口是应尽量封装一个单独配置文件）
    httpPre: any = 'http://127.0.0.1:8080/';
    // httpPre: any = 'http://192.168.8.113:9090/';
    acctListAPI: any = 'initPaymentNo.do';  // 账户查询API
    acctBalanceAPI: any = 'queryAcctNoBalance.do'; // 账户余额查询API
    showAcctAlert: any = false;
    selectedAcctNo: any;  // 选中账号
    accountsListArr: any; // 账户数据
    selectedAcctName: any; // 选中账户名称
    acctOpenBankName: any; // 开户行名
    // 起始-结束日期
    queryDate: any = {
        startTime: '',
        endTime: ''
    };

    nowClick: any;
    isShow: any;
    isClick: any;
    queryResultData: any; // 查询结果
    acctNo: any;
    acctName: any;
    balance: any;
    openBank: any;
    frozenBalance: any;
    useBalance: any;

    constructor(public http: HttpClient,
                public router: Router,
                public nav: NavController,
                public route: ActivatedRoute) {
        // ********************** 模拟默认数据 start **********************
        this.accountsListArr = [
            {'acctno': '6228480273164141816', 'acctname': '张三', 'openbank': '中信银行'},
            {'acctno': '6228480273164141819', 'acctname': '王', 'openbank': '建设银行'}
        ];

        this.selectedAcctNo = Utils.formatCardNumber(this.accountsListArr[0].acctno);
        this.acctOpenBankName = this.accountsListArr[0].openbank;
        this.selectedAcctName = this.accountsListArr[0].acctname;

        this.queryResultData = {
            'acctno': '6228480273164141816',
            'acctname': '张三',
            'openbank': '中信银行',
            'balance': '100万',
            'frozenbalance': '1000万',
            'usebalance': '1毛'
        };

        this.acctNo = Utils.formatCardNumber(this.queryResultData.acctno);
        this.acctName = this.queryResultData.acctname;
        this.openBank = this.queryResultData.openbank;
        this.balance = this.queryResultData.balance;
        this.frozenBalance = this.queryResultData.frozenbalance;
        this.useBalance = this.queryResultData.usebalance;
        // ********************** 模拟数据 end **********************

        this.initData();
        console.log('---' + this.queryDate.startTime + '---' + this.queryDate.endTime + '---' + this.selectedAcctNo);
    }

    ngOnInit() {}

    initData() {
        // 初始化账户数据
        this.apiUrl = this.httpPre + this.acctListAPI;
        this.loadingViewShow();
        this.header = new Headers({'Content-Type': 'application/json'});
        this.http.get(this.apiUrl, {headers: this.header}).subscribe((res: any) => {
            this.loadingViewHide();
            if (res && res.state === '1') {
                this.accountsListArr = res.data.paymentnoList;
                this.selectedAcctNo = Utils.formatCardNumber(this.accountsListArr[0].acctno);
                this.acctOpenBankName = this.accountsListArr[0].openbank;
                this.selectedAcctName = this.accountsListArr[0].acctname;
                console.log('suc =' + JSON.stringify(this.accountsListArr));
            } else {
                this.handAlert(res.msg);
            }
        }, error => {
            this.loadingViewHide();
            console.log('error=' + error);
            this.handAlert('请求出错，重新加载！');
        });
    }

    /**
     * 余额查询事件
     */
    queryDataEvent() {
        console.log('===' + this.queryDate.startTime + '\n' + '===' + this.queryDate.endTime + '\n' + '===' + this.selectedAcctNo);
        this.apiUrl = this.httpPre + this.acctBalanceAPI + '?acctno=' + this.selectedAcctNo.replace(/\s+/g, '');
        console.log('1111----' + this.apiUrl);
        this.header = new Headers({'Content-Type': 'application/json'});
        this.loadingViewShow();
        this.http.get(this.apiUrl, {headers: this.header}).subscribe((res: any) => {
            this.loadingViewHide();
            if (res && res.state === '1') {
                this.anyList = res.data;
                // this.navCtrl.push('AcctBalancePage', {data: this.anyList});
            } else {
                this.handAlert(res.msg);
            }
            console.log('===' + JSON.stringify(res));
        }, error => {
            this.loadingViewHide();
            console.log('error===' + error);
            this.handAlert('请求出错，重新加载!');
        });

        // this.httpservice.getData(this.apiUrl, this.params, function (data) {
        //     console.log('get success = ', data);
        // });
        //
        // this.httpservice.postData(this.apiUrl, this.params, function (data) {
        //     console.log('post success = ', data);
        // });
        //
        // this.header = new Headers({'Content-Type': 'application/json'});
        // this.http.post(this.apiUrl, '', {headers: this.header}).subscribe(data => {
        //     alert('suc' + JSON.stringify(data));
        //   }, error => {
        //     alert('err' + JSON.stringify(error));
        //   }
        // );
        //
        // // 实例化
        // this.header = new Headers({'Content-Type': 'application/json'});
        // // post请求
        // const body = JSON.stringify({'account': 'li', 'password': '123456'});
        // this.http.post(this.apiUrl, body, {headers: this.header}).subscribe(function (data) {
        //   console.log(data);
        //   alert(JSON.stringify(data));
        // }, error => {
        //   alert('err' + JSON.stringify(error));
        // });

    }

    /**
     * 选择 账户
     * @param acctNo
     * @param acctName
     * @param openBank
     */
    selectAccount(acctNo, acctName, openBank) {
        console.log(acctNo, '-', acctName, '-', openBank);
        this.selectedAcctNo = Utils.formatCardNumber(acctNo);
        this.selectedAcctName = acctName;
        this.acctOpenBankName = openBank;
        this.showAcctAlert = false;
    }

    /**
     * 展示可选账户
     * @param type
     */
    showAcctInfoAlert(type) {
        if (type === 'selectAcct') {
            this.showAcctAlert = true;
        }
    }

    /**
     * 隐藏弹框
     */
    hideAcctInfoAlert() {
        this.showAcctAlert = false;
    }

    /**
     * 重新账户加载数据
     */
    reloadAcctData() {
        // 初始化账户数据
        const that = this;
        setTimeout(function () {
            that.initData();
        }, 200);
    }

    /**
     * 显示加载动画
     */
    loadingViewShow() {
        // this.loading = this.loadingCtrl.create({
        //     spinner: 'bubbles',
        //     content: '正在加载数据'
        // });
        // this.loading.present();
    }

    /**
     * 隐藏加载动画
     */
    loadingViewHide() {
        // this.loading.dismiss();
    }

    // 处理银行卡格式 2
    formatCardNum(string) {
        return Utils.formatCardNumber(string);
    }

    // 回调异常弹框
    handAlert(msg) {
        // this.alertCtrl.create({
        //     message: msg,
        //     enableBackdropDismiss: false,
        //     buttons: [
        //         {
        //             text: '确定',
        //             handler: () => {
        //             }
        //         }
        //     ]
        // }).present();
    }

    showInfo(list) {
        if (this.nowClick == list) {
            this.nowClick = -1;
        } else {
            this.nowClick =  list;
        }
        if (this.isClick) {
            this.isShow = true;
            this.isClick = false;
        } else {
            this.isShow = false;
            this.isClick = true;
        }
    }


    goBack() {
        this.nav.goBack();
    }

}



